package qc.module.platform.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import qc.common.core.constants.QCAuthConstant;
import qc.common.core.exception.QCPromptException;
import qc.common.core.exception.QcTokenInvalidException;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.module.platform.dto.userCustomInfo.UserCustomInfoSetDto;
import qc.module.platform.entity.QcUserloginLogs;
import qc.module.platform.entity.QcUsers;
import qc.module.platform.service.UserAccessControlService;
import qc.module.platform.service.UserLoginLogService;
import qc.module.platform.service.UserService;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户自定义信息Controller
 *
 * @author QuCheng Tech
 * @since 2025/2/20
 */
@RestController
@RequestMapping("/usercustominfo")
public class UserCustomInfoController {
    @Autowired
    HttpServletRequest request;

    private UserService userService;

    private UserAccessControlService uacService;

    private UserLoginLogService userLoginLogService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setUserAccessControlService(UserAccessControlService uacService) {
        this.uacService = uacService;
    }

    @Autowired
    public void setUserLoginLogService(UserLoginLogService userLoginLogService) {
        this.userLoginLogService = userLoginLogService;
    }

    @GetMapping("/get")
    public String get() throws QcTokenInvalidException {
        try {
            QcUsers user = getUserEntity();

            return user.getCustominfo();
        } catch (QCPromptException e) {
            //返回异常提示信息文字
            return e.getMessage();
        }
    }

    @PostMapping("/set")
    public String set(@RequestBody UserCustomInfoSetDto dto) throws QcTokenInvalidException {
        if (dto == null)
            return "设置用户自定义信息对象不能为空";

        try {
            QcUsers user = getUserEntity();

            //设置不成功，返回提示
            if (userService.setCustomInfo(user.getId().intValue(), dto.getInfo()) == false)
                return "设置失败";
        } catch (QCPromptException e) {
            //返回异常提示信息文字
            return e.getMessage();
        }

        return QCUnifyReturnValue.Success();
    }

    /***
     * 根据请求头中的token获取当前登录用户信息，抛出异常
     *
     * @return qc.module.platform.entity.QcUsers
     * @author QuCheng Tech
     * @since 2025/2/20
     */
    QcUsers getUserEntity() throws QCPromptException, QcTokenInvalidException {
        String token = request.getHeader(QCAuthConstant.TOKEN_HEADER_KEY);

        //根据token获取登录日志，判断登录信息是否有效
        QcUserloginLogs loginLog = userLoginLogService.getUserLoginLogByToken(token, true);

        QcUsers user = userService.getEntity(loginLog.getUid());
        if (user == null)//用户信息不存在，抛出异常提示
            throw new QCPromptException("用户信息不存在");

        return user;
    }
}
